<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style lang="">
    .zoom {
        cursor: move;
        fill: none;
        pointer-events: all;
    }
</style>
</head>
<body>
    <script src="https://d3js.org/d3.v4.min.js"></script>
<script>
    //画布长宽
    var svgWidth = 800;
    var svgHeight = 300;

    //画布在容器内的大小
    var margin = { top: 30, right: 40, bottom: 50, left: 60 };

    //绘制图标的宽高
    var width = svgWidth - margin.left - margin.right;
    var height = svgHeight - margin.top - margin.bottom;

    //圆信息
    var originalCircle = {
        "cx": -150,
        "cy": -15,
        "r": 20
    };

    //图表容器
    var svgViewport = d3.select("body")
        .append('svg')
        .attr('width', svgWidth)
        .attr('height', svgHeight)

    //创建横坐标比例尺
    // 根据画布宽度[0,width],等量取[-200,100]的值
    var xAxisScale = d3.scaleLinear()
        .domain([-200, -100])
        .range([0, width]);

    //创建纵坐标比例尺
    var yAxisScale = d3.scaleLinear()
        .domain([-10, -20])
        .range([height, 0]);

    //横坐标纵坐标容器
    var xAxis = d3.axisBottom(xAxisScale);
    var yAxis = d3.axisLeft(yAxisScale);

    //图表缩放绑定方法
    var zoom = d3.zoom()
        .on("zoom", zoomFunction);

    //在svg容器内插入g标签并绑定缩放函数并使用transform固定该标签到横纵坐标上
    var innerSpace = svgViewport.append("g")
        .attr("class", "inner_space")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .call(zoom);

    //创建一个圆并在坐标系上设置圆的位置和半径
    var circles = innerSpace.append('circle')
        .attr("id", "circles")
        .attr("cx", xAxisScale(originalCircle.cx))
        .attr("cy", yAxisScale(originalCircle.cy))
        .attr('r', originalCircle.r)

    //绘制横坐标
    var gX = innerSpace.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    //绘制纵坐标
    var gY = innerSpace.append("g")
        .attr("class", "axis axis--y")
        .call(yAxis);

    //创建一个rect绑定缩放事件
    var view = innerSpace.append("rect")
        .attr("class", "zoom")
        .attr("width", width)
        .attr("height", height)
        .call(zoom)

    // 初始化直方图
    var data = d3.range(1000).map(d3.randomNormal(80, 10));
    data.sort(function (a, b) { return a - b; });
    console.log(data)

    function zoomFunction() {
        // 基于事件创建一个新的比例尺
        var new_xScale = d3.event.transform.rescaleX(xAxisScale)
        var new_yScale = d3.event.transform.rescaleY(yAxisScale)

        // 更新横坐标和纵坐标
        gX.call(xAxis.scale(new_xScale));
        gY.call(yAxis.scale(new_yScale));

        // 更新圆的位置
        circles.attr("transform", d3.event.transform)
    };
</script>
</body>
</html>